package com.jason.core.wilddog.handler;

import com.wilddog.client.DataSnapshot;
import com.wilddog.client.SyncError;
import com.wilddog.client.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;


/**
 * @author he peng
 * @create 2017/12/18 10:26
 * @see
 */
public abstract class AbstractTransactionHandler implements Transaction.Handler {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractTransactionHandler.class);
    protected Object data;

    @Override
    public void onComplete(SyncError syncError, boolean committed, DataSnapshot dataSnapshot) {
        if (LOG.isInfoEnabled()) {
            if (Objects.nonNull(syncError)) {
                LOG.info("wilddog sync transaction operation error , code -> {} , msg -> {} , details -> {} , " +
                          "node -> {} , key -> {} , data {} " ,
                        syncError.getErrCode() , syncError.getMessage() , syncError.getDetails() ,
                        dataSnapshot , dataSnapshot.getKey() , this.data);
            }

            if (committed) {
                LOG.info("transaction committed , node -> {} , key -> {} , data {} " ,
                            dataSnapshot , dataSnapshot.getKey() , this.data);
            } else {
                LOG.info("transaction not committed , node -> {} , key -> {} , data {} " ,
                            dataSnapshot , dataSnapshot.getKey() , this.data);
            }
        }
        internalComplete(syncError , committed , dataSnapshot);
    }

    protected abstract void internalComplete(SyncError syncError, boolean committed, DataSnapshot dataSnapshot);


    public Object getData() {
        return data;
    }

    public AbstractTransactionHandler setData(Object data) {
        this.data = data;
        return this;
    }

    @Override
    public String toString() {
        return "TransactionHandler{" +
                "data=" + data +
                '}';
    }
}
